package com.decent.ejfadmin.finance.service.impl;

import com.decent.ejfadmin.common.bean.*;
import com.decent.ejfadmin.common.exception.OperateFailException;
import com.decent.ejfadmin.common.util.Constants;
import com.decent.ejfadmin.common.util.DingTalkMessagePush;
import com.decent.ejfadmin.common.util.WithHoldDes;
import com.decent.ejfadmin.finance.dao.SupplyFinanceDao;
import com.decent.ejfadmin.finance.service.SupplyFinanceService;
import com.decent.ejfadmin.finance.service.WithdrawService;
import com.decent.ejfadmin.user.dao.UserDao;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 提现订单
 *
 * @author weicx
 * @date 2018/08/16
 */
@Service
public class WithdrawServiceImpl implements WithdrawService {
    @Autowired
    private SupplyFinanceDao supplyFinanceDao;
    @Autowired
    private SupplyFinanceService supplyFinanceService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private DingTalkMessagePush dingTalkMessagePush;

    /**
     * 手动修改提现消费明细
     *
     * @param withdrawRecord 提现订单
     * @return 返回
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int modifyWithdraw(WithdrawRecord withdrawRecord) {
        if (supplyFinanceDao.updateWithdrawRecordRecall(withdrawRecord) != 1) {
            throw new RuntimeException(String.format("更改提现订单[%s]状态为[%s]失败", withdrawRecord.getOrderId(), withdrawRecord.getState()));
        }
        if (Constants.EXCEPTION_STATE.equals(withdrawRecord.getState())) {
            return 1;
        }
        SupplyBalance supplyBalance = supplyFinanceService.querySupplyBalanceVersion(withdrawRecord.getUserId());
        //提现成功
        if (Constants.SUCCESS_STATE.equals(withdrawRecord.getState())) {
            //修改余额,新增消费明细
            SupplyConsumption supplyConsumption1 = new SupplyConsumption();
            supplyConsumption1.setUserId(withdrawRecord.getUserId());
            supplyConsumption1.setOrderId(withdrawRecord.getOrderId());
            supplyConsumption1.setChannel(withdrawRecord.getWithdrawChannel());
            supplyConsumption1.setMoney(withdrawRecord.getPrice().multiply(BigDecimal.valueOf(-1)));
            supplyConsumption1.setType(SupplyConsumption.WITHDRAW);
            supplyConsumption1.setBalance(supplyBalance.getBalance().subtract(withdrawRecord.getPrice()));
            supplyConsumption1.setConsumeType(SupplyConsumption.WITHDRAW_SUCCESS);
            //新增消费明细
            int row = supplyFinanceDao.createSupplyConsumption(supplyConsumption1);
            if (row != 1) {
                throw new OperateFailException("{" + supplyConsumption1.getUserId() + "}|{" + supplyConsumption1.getOrderId() + "}新增消费明细异常");
            }
            //如果有手续费需要新增手续费的资金明细
            if (withdrawRecord.getServicePrice().compareTo(BigDecimal.ZERO) > 0) {
                supplyConsumption1.setMoney(WithdrawRecord.SERVICE_MONEY.multiply(BigDecimal.valueOf(-1)));
                supplyConsumption1.setConsumeType(SupplyConsumption.SERVICE_TYPE);
                //当前余额= 余额-提现金额-手续费
                supplyConsumption1.setBalance(supplyBalance.getBalance().subtract(withdrawRecord.getPrice()).subtract(WithdrawRecord.SERVICE_MONEY));
                //新增手续费消费明细
                row = supplyFinanceDao.createSupplyConsumption(supplyConsumption1);
                if (row != 1) {
                    throw new OperateFailException("{" + supplyConsumption1.getUserId() + "}|{" + supplyConsumption1.getOrderId() + "}新增手续费消费明细异常");
                }
            }
            //修改余额
            int error = supplyFinanceDao.updateBalanceCallBack(supplyBalance, withdrawRecord.getPrice().add(withdrawRecord.getServicePrice()));
            if (error == 0) {
                throw new OperateFailException("{" + withdrawRecord.getOrderId() +
                        "} 余额修改失败,余额" + supplyBalance.getBalance() + "提现金额" + withdrawRecord.getPrice());
            }
        }
        if (Constants.FAIL_STATE.equals(withdrawRecord.getState())) {
            //修改用户冻结金额
            withdrawRecord.setPrice(withdrawRecord.getPrice().add(withdrawRecord.getServicePrice()));
            int row = supplyFinanceDao.updateTransferFail(withdrawRecord);
            if (row != 1) {
                throw new OperateFailException("{" + withdrawRecord.getOrderId() + "} 失败提现记录修改失败");
            }
        }
        SupUser user = userDao.queryUserById(withdrawRecord.getUserId());
        if (user.getSupInfo() != null && StringUtils.isNotBlank(user.getSupInfo().getOpenId())) {
            DbWithdrawRecord dbWithdrawRecord = supplyFinanceDao.queryDbWithdrawRecord(withdrawRecord.getOrderId());
            NotifyWeChatBean notifyWeChatBean = new NotifyWeChatBean();
            notifyWeChatBean.setOpenid(user.getSupInfo().getOpenId());
            notifyWeChatBean.setLoginAccount(user.getAccount());
            //兼容支付宝提现
            if (SupplyConsumption.BANK.equals(dbWithdrawRecord.getWithdrawChannel())) {
                notifyWeChatBean.setWithdrawAccount(WithHoldDes.decodeValue(dbWithdrawRecord.getBankSalt(), dbWithdrawRecord.getTransferNo()));
            } else {
                notifyWeChatBean.setWithdrawAccount(dbWithdrawRecord.getAlipay());
            }
            notifyWeChatBean.setMoney(dbWithdrawRecord.getPrice());
            notifyWeChatBean.setStartTime(DateFormatUtils.format(dbWithdrawRecord.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
            notifyWeChatBean.setOrderId(withdrawRecord.getOrderId());
            notifyWeChatBean.setStatus(dbWithdrawRecord.getState());
            notifyWeChatBean.setRealName(dbWithdrawRecord.getCertName());
            dingTalkMessagePush.withdrawMessagePushingToWeiChat(notifyWeChatBean);
        }
        return 1;
    }
}
